package com.apbetioli.mapr.place.webservice;

import com.apbetioli.mapr.place.control.PlacesControl;
import com.apbetioli.mapr.place.schema.PlacesManager;
import com.apbetioli.mapr.util.properties.PropertiesLoaderImpl;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 *
 * @author alexandre
 */
@WebService()
public class WSPlaces {

    private JAXBContext jc;
    private final String SCHEMA_PACKAGE = PropertiesLoaderImpl.getValue("config.properties", "place.schema");

    /**
     * Web service operation
     */
    @WebMethod(operationName = "process")
    public String process(
            @WebParam(name = "xml")
            final String xml,
            
            @WebParam(name = "projectKey")
            final String projectKey) {

        try {
            jc = JAXBContext.newInstance(SCHEMA_PACKAGE);

            PlacesManager pm = unmarshall(xml);
            PlacesControl pc = new PlacesControl();
            PlacesManager response = pc.process(pm, projectKey);
            return marshall(response);

        } catch (Exception ex) {
            Logger.getLogger(WSPlaces.class.getName()).log(Level.SEVERE, null, ex);

            return "<? xml version=\"1.0\"?>                          \n" +
                    "<PlacesManager>                                   \n" +
                    "    <Error>                                       \n" +
                    "       <Message>Exception</Message>               \n" +
                    "       <Details>" + ex.getMessage() + "</Details> \n" +
                    "    </Error>                                      \n" +
                    "</PlacesManager>                                  \n";
        }
    }

    private PlacesManager unmarshall(String xml) throws JAXBException {

        Unmarshaller um = jc.createUnmarshaller();

        StringReader sr = new StringReader(xml);
        BufferedReader br = new BufferedReader(sr);
        PlacesManager pm = (PlacesManager) um.unmarshal(br);

        return pm;
    }

    private String marshall(PlacesManager pm) throws JAXBException {

        StringWriter sw = new StringWriter();
        BufferedWriter bw = new BufferedWriter(sw);

        Marshaller marsh = jc.createMarshaller();
        marsh.marshal(pm, bw);

        return sw.toString();
    }
}
